package com.sigmazero13.MKDummy.components;

import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sigmazero13.MKDummy.R;

public class TacticsSelector extends LinearLayout {
	
	private Context mContext;
	private Set<Integer> curAvailable;
	private static Integer TEXT_ID = 999;
	private static Integer IMAGE_ID = 1000;
	
	public TacticsSelector(Context context) {
		super(context);
		mContext = context;
		commonSetup();
	}

	public TacticsSelector(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		commonSetup();
	}
	
	private void commonSetup() {
		this.setOrientation(LinearLayout.HORIZONTAL);
		this.setGravity(Gravity.CENTER_HORIZONTAL);
		
		curAvailable = new HashSet<Integer>();
		
		for (Integer i = 1; i <= 6; i++) {
			curAvailable.add(i);
			RelativeLayout main = new RelativeLayout(mContext);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			main.setLayoutParams(layoutParams);
			main.setPadding(15, 10, 15, 10);
			
			TextView tv = new TextView(mContext);
			tv.setText(i.toString());
			tv.setId(TEXT_ID);
			tv.setTextSize(mContext.getResources().getDimension(R.dimen.player_name_size));
			tv.setTypeface(tv.getTypeface(), Typeface.BOLD);
			
			ImageView iv = new ImageView(mContext);
			iv.setImageDrawable(null);
			iv.setId(IMAGE_ID);
			iv.setPadding(0, 20, 0, 0);
			
			main.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					toggleValue(v);
				}
			});
			
			main.addView(tv);
			main.addView(iv);
			
			this.addView(main);
		}
	}
	
	public Set<Integer> getAvailableValues() {
		return curAvailable;
	}
	
	public void resetTactics() {
		for (Integer i = 1; i <= 6; i++) {
			if (!curAvailable.contains(i)) {
				toggleValue(this.getChildAt(i-1));
			}
		}
	}
	
	public void selectTactic(int tactic) {
		if (curAvailable.contains(tactic)) {
			toggleValue(this.getChildAt(tactic-1));
		}
	}
	
	private void toggleValue(View sel) {
		TextView tv = (TextView)sel.findViewById(TEXT_ID);
		ImageView iv = (ImageView)sel.findViewById(IMAGE_ID);
		
		Integer i = Integer.parseInt(tv.getText().toString());
		
		if (curAvailable.contains(i)) {
			curAvailable.remove(i);
			iv.setImageResource(R.drawable.x);
		} else {
			curAvailable.add(i);
			iv.setImageDrawable(null);
		}
	}

}
